#!/bin/bash
#set -x
BASE_DIR=`cd $(dirname $0);pwd`
REGISTRY_ADDRESS=registry.cn-hangzhou.aliyuncs.com
PROGECT=shnlearning
USER_NAME="我叫清葵雨露"
fouction_login(){
	echo "输入要推送的镜像仓库密码"
        docker login --username=${USER_NAME} ${REGISTRY_ADDRESS} && echo "登录成功" || exit 404
}

fouction_pull(){
        read -p "请输入要拉取的镜像地址:" GCR_IMAGE
	
        docker pull ${GCR_IMAGE} && echo "${GCR_IMAGE} 拉取成功" || exit 404
}

fouction_tag(){
        NUMBER=$(expr `echo "${GCR_IMAGE}" |awk -F '/' '{print NF}'` - 1)
	#判断非docker镜像仓库镜像
        if [ "${NUMBER}" -gt '1' ];then
		#获取镜像名称
                REPOSITORY_NAME=`echo "${GCR_IMAGE}" |awk -F ':' '{print $1}' |awk -F '/' '{print $NF}'`
		
		#判断镜像版本是否携带sha256并获取镜像tag
		EXIST=`echo ${GCR_IMAGE} |grep -o 'sha256'`
		if [ -z "${EXIST}" ];then
                	REPOSITORY_TAG=`echo "${GCR_IMAGE}" |awk -F '[:]' '{print $NF}'`
		else
			#如果有sha256就多了一个分隔符@
                	REPOSITORY_TAG=`echo "${GCR_IMAGE}" |awk -F '[:｜@]' '{print $2}'`
		fi

                docker tag ${GCR_IMAGE} ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG}

        #判断docker仓库的镜像
        elif [ "${NUMBER}" -lt '1' ];then
                REPOSITORY_NAME=`echo "${GCR_IMAGE}" |awk -F ':' '{print $1}'`
                REPOSITORY_TAG=`echo "${GCR_IMAGE}" |awk -F ':' '{print $2}'` 
                docker tag ${GCR_IMAGE} ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG}
        #判断docker仓库的镜像
        elif [ "${NUMBER}" -eq '1' ];then
                REPOSITORY_NAME=`echo "${GCR_IMAGE}" |awk -F '[/:]' '{print $2}'`
                REPOSITORY_TAG=`echo "${GCR_IMAGE}" |awk -F '[/:]' '{print $3}'`
                docker tag ${GCR_IMAGE} ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG}
        fi
}

fouction_push(){
        docker push ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG} && docker rmi -f ${GCR_IMAGE} ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG}
	echo "新镜像地址为: ${REGISTRY_ADDRESS}/${PROGECT}/${REPOSITORY_NAME}:${REPOSITORY_TAG}"
}


fouction_login
fouction_pull
fouction_tag
fouction_push
